/**
 * author: Hanflyee  flyee1980@163.com
 * vision: v1.0
 * data: 2009-7-25
 */
package com.flyee.controller{
	
	import com.flyee.controller.timer.CartoonTimer;
	import com.flyee.controller.tools.cartoon.EquipManager;
	import com.flyee.io.Config;
	import com.flyee.model.Charactor;
	import com.flyee.model.Monster;
	import com.flyee.service.pool.EffectDepot;
	import com.flyee.service.pool.ObjectCollection;
	import com.flyee.service.pool.RelationMV;
	import com.flyee.utils.Constants;
	import com.flyee.utils.EventUtils;
	import com.flyee.utils.MyLog;
	import com.flyee.utils.Obsevable;
	import com.flyee.utils.Obsever;
	import com.flyee.utils.load.StackLoader;
	import com.flyee.utils.load.model.LoaderModel;
	import com.flyee.utils.load.processor.LoadLevelType;
	import com.flyee.utils.load.processor.LoadReturnType;
	import com.flyee.viewer.CharactorViewer;
	import com.flyee.viewer.MonsterViewer;
	import com.flyee.viewer.PickUpItemViewer;
	
	import flash.display.Bitmap;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import mx.core.Application;
	
	/**
	 * 人物动画控制器 ， 控制动画TIMER
	 */
	public class CharacterCartoonController extends Obsevable implements Obsever{
		
		[Inject]
		public var equipManager : EquipManager;
		
		public function CharacterCartoonController(){
			
		}
		
		public function execute(o : Obsevable, command : String=null, args : * = null) : void {
			switch(command){
				case "changeActionDirect" : 
					changeActionDirect(args[0], args[1], args[2]);
					break ;
				case "playerDie" : 
					playerDie(args[0]);
					break ;
				default :
					break;
			}
		}
		
		/**
		 * 初始化玩家Viewer 
		 */
		public function initCharacterViewer(char : Charactor) : CharactorViewer {
			var charViewer : CharactorViewer = new CharactorViewer();
			charViewer.setNameText(char.name);
			var bmp : Bitmap = new Bitmap(EffectDepot.loadingPlayer.bitmapData);
			bmp.x = -10;
			bmp.y = 30;
			charViewer.charactorContainer.addChild(bmp);
//			charViewer.scaleX = 0.5;
//			charViewer.scaleY = 0.5;			
			if(ObjectCollection.master == char){
				ObjectCollection.masterViewer = charViewer;
				/**加载主角光环标记*/
				charViewer.addChildAt(EffectDepot.masterTag, 0);
				EffectDepot.masterTag.x = 5;
				EffectDepot.masterTag.y = -5;
			}else{
				//将人物Viewer加入到Viewer对象集合
				ObjectCollection.charactorViewerMap.put(charViewer.vid, charViewer);
				//保存人物数据和人物Viewer的对应关系
				ObjectCollection.relationArray.push(new RelationMV(char.mid, charViewer.vid));				
			}	
			loadCharacterPlate(char, charViewer);	
			loadWeapon(charViewer, Config.getInstance().getResourcePath() + "resource/weapon.swf");
			charViewer.addEventListener(MouseEvent.CLICK, chooseTarget);
			return charViewer;
		}

		/**
		 * 加载武器动画 
		 */
		public function loadWeapon(playerV : CharactorViewer, url : String) : void {
			var obj : Object = {x:40, y:-160, view:playerV};
			var loader : StackLoader = new StackLoader();
			loader.load(url, LoadLevelType.LV_1, null, loaderWeaponHandler, LoadReturnType.RETURN_LOADER, obj);
		}
		
		private function loaderWeaponHandler(loader : LoaderModel) : void {
			var container : CharactorViewer = loader.memo.view as CharactorViewer;
			container.weaponCartoon = loader.content as MovieClip;
			container.weaponContainer.addChild(container.weaponCartoon);
			container.weaponCartoon.x += loader.memo.x;
			container.weaponCartoon.y += loader.memo.y;
			container.weaponCartoon.stop();
		}
		
		/**
		 * 加载玩家Viewer动作图板 
		 */
		public function loadCharacterPlate(char : Charactor, charViewer : CharactorViewer, changeId : String = null) : void {
//			equipManager.timer.start();
			if(changeId)
				ObjectCollection.master.equipID = changeId;
			equipManager.getEquip(char.gcode, charViewer.plateArray, loadCharacterPlateHandler, changeId);
			
		}
		
		public function loadCharacterPlateHandler(id : String) : void {			
			var char : Charactor = ObjectCollection.getCharacter(id);
			var charViewer : CharactorViewer = ObjectCollection.getCharacterViewerByMid(char.mid);

			var cartoonTimer : CartoonTimer = null;
			if(!ObjectCollection.cartoonTimerMap.containsKey(charViewer.vid)){
//				charViewer.graphics.clear();
				cartoonTimer = new CartoonTimer(char, charViewer, Constants.FRAME_ACTION_TIME);
				ObjectCollection.cartoonTimerMap.put(charViewer.vid, cartoonTimer);
			}else{
				cartoonTimer = ObjectCollection.cartoonTimerMap.get(charViewer.vid);
			}
			if(char.hp != 0){
				charViewer.weaponContainer.visible = true;
				charViewer.specialContainer.visible = true;
			}
			cartoonTimer.autoPlay = true;
			cartoonTimer.setCurrentStatus(1,0,0);
			cartoonTimer.timerHandle();	
			charViewer.nameText.x = charViewer.width / 2 - charViewer.nameText.width / 2;	
		}
		
		/**
		 * 改变玩家 动作，方向 
		 */
		public function changeActionDirect(charViewer : CharactorViewer, action : int, direct : int = -1, frame : int = -1) : void {
			if(charViewer.plateArray.length == 0) return ;
			if(!ObjectCollection.cartoonTimerMap.containsKey(charViewer.vid)) return ;
			var cartoonTimer : CartoonTimer = ObjectCollection.cartoonTimerMap.get(charViewer.vid);
//			if(direct == -1)
//				cartoonTimer.setCurrentStatus(action, cartoonTimer.getDirect(), cartoonTimer.getFrame());
//			cartoonTimer.setCurrentStatus(action, direct+1, cartoonTimer.getFrame());
			cartoonTimer.setCurrentStatus(action
										, (direct == -1) ? cartoonTimer.getDirect() : direct+1
										, (frame == -1) ? cartoonTimer.getFrame() : frame);
//			trace("----" + charViewer.vid + " : " + cartoonTimer.getDirect() + "----");
		} 
		
		/**
		 * 设置其他玩家可见 
		 */
		public function setPlayersVisible(value : Boolean) : void {
			for each(var charViewer : CharactorViewer in ObjectCollection.charactorViewerMap.values()){
				if(value == charViewer.playerVisible) continue;
				setPlayerVisible(value, charViewer);
			}
		}
		
		public function setPlayerVisible(value : Boolean, charViewer : CharactorViewer) : void {
			charViewer.playerVisible = value;
			charViewer.charactorContainer.visible = value;			
			charViewer.specialContainer.visible = value;
			var cartoonTimer : CartoonTimer = ObjectCollection.cartoonTimerMap.get(charViewer.vid) as CartoonTimer;
			if(value){
				var char : Charactor = ObjectCollection.charactorMap.get(ObjectCollection.getMidByVid(charViewer.vid));
				this.loadCharacterPlate(char, charViewer);
				cartoonTimer.autoPlay = value;
			}else{				
				cartoonTimer.autoPlay = value;
				if(charViewer.charactorContainer.numChildren != 0)
					charViewer.charactorContainer.removeChildAt(0);
				if(charViewer.specialContainer.numChildren != 0)
					charViewer.specialContainer.removeChildAt(0);
				charViewer.dispose();
			}
		}
		
		/**
		 * 选择目标 
		 */
		public function chooseTarget(event : MouseEvent) : void {
			event.stopPropagation();
			var targetViewer : CharactorViewer = event.currentTarget as CharactorViewer;			
			var target : Charactor = ObjectCollection.getCharacterByVid(targetViewer.vid);	
			if(target.hp == 0){
				if(target is Monster){
					var monsterViewer:MonsterViewer = ObjectCollection.
								getCharacterViewerByMid(target.mid) as MonsterViewer;
					var lostItems:Array = monsterViewer.getLostItems();
					if(lostItems.length > 0){
						var viewer:PickUpItemViewer = new PickUpItemViewer();
						viewer.x = (Application.application.width - viewer.width)/2;
						viewer.y = (Application.application.height - viewer.height)/2;
						viewer.fill(target,lostItems);
						lostItems.splice(0);
						lostItems = null;
						ObjectCollection.uiContainer.addChild(viewer);
					}
				}
				return ;
			}
			var srcTargetViewer : CharactorViewer;
			if(ObjectCollection.master.target != null)
				srcTargetViewer = ObjectCollection.getCharacterViewerByMid(ObjectCollection.master.target.mid)
			//if(target == ObjectCollection.master.target) return ;
			if(srcTargetViewer!=null && srcTargetViewer.contains(EffectDepot.targetTag))
				srcTargetViewer.removeChild(EffectDepot.targetTag);
			if(target != ObjectCollection.master){
				targetViewer.addChildAt(EffectDepot.targetTag, 0);
				EffectDepot.targetTag.x = 5;
				EffectDepot.targetTag.y = -5;
			}
			ObjectCollection.master.target = target;
			
			ObjectCollection.targetWindowViewer.targetName = target.name;
			ObjectCollection.targetWindowViewer.hp = target.hp;
			ObjectCollection.targetWindowViewer.mp = target.mp;
			ObjectCollection.targetWindowViewer.visible = true;
			
			
		}
		
		/**
		 * 表现 死亡效果 
		 */
		public function playerDie(playerV : CharactorViewer) : void {
			var timer : CartoonTimer = ObjectCollection.cartoonTimerMap.get(playerV.vid) as CartoonTimer;
			if(timer == null) return;
			timer.reset();
			var obj : Object = {x:0, y:80, view:playerV};
			var loader : StackLoader = new StackLoader();
			loader.load(Config.getInstance().getResourcePath() + "resource/die.swf", LoadLevelType.LV_1, null, loadDieCartoonHandler, LoadReturnType.RETURN_LOADER, obj);
			while(playerV.charactorContainer.numChildren > 0){
				playerV.charactorContainer.removeChildAt(0);
			}
			while(playerV.specialContainer.numChildren > 0){
				playerV.specialContainer.removeChildAt(0);
				playerV.specialContainer.visible = false;
			}
			while(playerV.weaponContainer.numChildren > 0){
				playerV.weaponContainer.removeChildAt(0);
				playerV.weaponContainer.visible = false;
			}
			if(timer.char.target is Charactor && playerV is MonsterViewer){
				var mon : Monster = timer.char as Monster
				getExp(timer.char.target, mon.expMonster);
			}
		}
		
		/**怪物死亡后，人物获得经验*/
		public function getExp(player : Charactor, exp : Number) : void {
			player.exp += exp;
			if(player.exp >= player.nextExp){
				player.exp = player.exp - player.nextExp;
				player.nextExp = (player.lvl + 1) * Constants.LEVEL_UP_EXP;
				player.lvl++;				
				dealLevelUp(player);				
			}
			this.setChanged();
			this.notifyObsevers("updateExp",player.exp,player.nextExp);
		}
		
		/**人物升级*/
		public function dealLevelUp(player : Charactor) : void {

			var playerV : CharactorViewer = ObjectCollection.getCharacterViewerByMid(player.mid);
			var mc : MovieClip = EffectDepot.getLevelUpEffect();
			mc.scaleX = 2.5;
			mc.scaleY = 2.5;
			playerV.specialContainer.addChild(mc);
			mc.x = -80;
			mc.y = -180;
			var obj : Object = {container:playerV.specialContainer, cartoon:mc};			
			var timer : Timer = new Timer(1000, 1);
			EventUtils.addListener(timer, TimerEvent.TIMER_COMPLETE, levelUpOver, obj);
			timer.start();
			this.setChanged();
			this.notifyObsevers("updateLevel",player.lvl);
		}
		
		private function levelUpOver(event : TimerEvent, obj : Object = null) : void {
			var container : DisplayObjectContainer = obj.container as DisplayObjectContainer;
			var cartoon : MovieClip = obj.cartoon as MovieClip;
			container.removeChild(cartoon);
			var t : Timer = event.target as Timer;
			t.removeEventListener(TimerEvent.TIMER_COMPLETE, levelUpOver);
		}
		
		/**死亡效果处理*/
		public function loadDieCartoonHandler(loader : LoaderModel) : void {
			var container : CharactorViewer = loader.memo.view as CharactorViewer;
//			container.cartoon = loader.content as MovieClip;
			container.charactorContainer.addChild(loader);
			loader.x += loader.memo.x;
			loader.y += loader.memo.y;
		}
		
	}
	
}